process.env.SERVER_RENDER = true;

const Koa = require('koa')
const Webpack = require('webpack')
const webpackConfig = require('../webpack.config')
const koaWebpack = require('koa-webpack');
const serve = require('koa-static');
// const pugViewsMiddleware = require('./pugViews')
// const devMiddleware = require('webpack-dev-middleware');
// const devMiddleware = require('koa-webpack-middleware').devMiddleware
const pug = require('pug');
const routes = require('../src/renderServer/routes');
const app = new Koa();
// const koaBody = require('koa-body');
var MemoryFileSystem = require("memory-fs");
var memfs = new MemoryFileSystem()

const compiler = Webpack(webpackConfig);

// app.use(pugViewsMiddleware({ compiler }))

// app.use(devMiddleware(compiler, {
//     // noInfo: true,
//     publicPath: webpackConfig.output.publicPath,
//     stats: {
//         colors: true
//     }
// }));

const setDevServer = async () => {
    const middleware = await koaWebpack({
        compiler,
        devMiddleware: {
            methods: ['GET'],
            logLevel: 'warn',
            // publicPath: webpackConfig.output.publicPath
        },
        hotClient: {
            allEntries: true,
            // autoConfigure: false
            // server: app
        },
    });
    app.use(middleware)

    // app.use(convert(body()));

    app.use(async (ctx, next) => {
        if (ctx.render) return next();
        // const filename = path.resolve(webpackConfig.output.path, 'index.html')
        // ctx.response.type = 'html'
        // ctx.response.body = middleware.devMiddleware.fileSystem.createReadStream(filename)
        // memfs

        ctx.response.render = ctx.render = async (pagePath, locals = {}) => {
            const state = Object.assign(locals, ctx.state || {});
            // console.log(state)

            let fileBuf = middleware.devMiddleware.fileSystem.readFileSync(compiler.outputPath + `/pages/${pagePath}`);
            // console.log(fileBuf)
            let htmlFn = pug.compile(fileBuf.toString(),{
                filename: compiler.outputPath + `/pages/${pagePath}`
            });

            ctx.type = 'text/html';
            ctx.body = htmlFn(state);
            // return render()
        }
        return next()
    })

    routes(app);
    app.use(serve('../src/'));
    app.listen(9005);
    console.log('dev server listen at: http://localhost:9005')
}
setDevServer();

